﻿using System.Text.Json.Serialization;

namespace Sgr.EventBus
{
    /// <summary>
    /// 集成事件基类
    /// </summary>
    public record IntegrationEvent
    {
        /// <summary>
        /// 事件唯一标识，默认为 Guid (N)
        /// </summary>
        [JsonPropertyName("id")]
        public string Id { get; init; } = Guid.NewGuid().ToString("N");

        /// <summary>
        /// 上游命令ID（因果链），用于调用链追踪
        /// </summary>
        [JsonPropertyName("cau_id")]
        public string? CausationId { get; init; }

        /// <summary>
        /// 关联ID（整条业务链路的跟踪ID）
        /// </summary>
        [JsonPropertyName("cor_id")]
        public string? CorrelationId { get; init; }

        /// <summary>
        /// 事件产生的时间（UTC）
        /// </summary>
        [JsonPropertyName("ts")]
        public DateTime Timestamp { get; init; } = DateTime.UtcNow;

        /// <summary>
        /// 构造函数
        /// </summary>
        public IntegrationEvent() { }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="correlationId">上游命令ID（因果链），用于调用链追踪</param>
        /// <param name="causationId">关联ID（整条业务链路的跟踪ID）</param>
        public IntegrationEvent(string? correlationId = null, string? causationId = null)
        {
            CorrelationId = correlationId;
            CausationId = causationId;
        }

        /// <summary>
        /// 快捷工厂
        /// </summary>
        public static IntegrationEvent Create(string? correlationId = null, string? causationId = null)
            => new IntegrationEvent(correlationId, causationId);

        /// <summary>
        /// 带 CorrelationId 的副本
        /// </summary>
        public IntegrationEvent WithCorrelation(string correlationId)
            => this with { CorrelationId = correlationId };

        /// <summary>
        /// 带 CausationId 的副本
        /// </summary>
        public IntegrationEvent WithCausation(string causationId)
            => this with { CausationId = causationId };

        public override string ToString()
            => $"IntegrationEvent {{ Id = {Id}, CorrelationId = {CorrelationId ?? "null"}, CausationId = {CausationId ?? "null"}, Timestamp = {Timestamp:o} }}";
    }
}